package com.sdy.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mysql.jdbc.StringUtils;
import com.sdy.model.Department;
import com.sdy.util.AjaxDone;

public class DepartmentController extends Controller {
	private Department dao = Department.dao;
	
	public void index(){
		
	}
	
	public void datagrid() {
		try {
			List<Department> departmentList = dao.find("SELECT t1.`id`, t1.`deptId`, t1.`name`, t2.`name` AS parentName , t1.`level` FROM department t1 LEFT JOIN department t2 ON t1.`parentId` = t2.`id`;");
			renderJson(departmentList);
		} catch (Exception e ){
			e.printStackTrace();
		}
	}
	
	public void doAdd() {
		AjaxDone j = new AjaxDone();
		try {
			Department department = getModel(Department.class);
			String deptId = department.getStr("deptId");
			if(StringUtils.isNullOrEmpty(deptId)) {
				j.setErrorMsg("部门编号不能为空!");
			} else {
				List<Department> list = dao.find("select * from department where deptId = ?", deptId);
				if(list == null || list.size() == 0) {
					department.save();
				} else {
					j.setErrorMsg("该部门编号已存在，请重新输入!");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderJson(j);
	}
	
	/**
	 * 根据partneId查找所属子部门
	 */
	public void searchDeptByPId() {
		try {
			String pid = getPara("pid");
			List<Department> departmentList = new ArrayList<Department>();
			if(StringUtils.isNullOrEmpty(pid)) {
				departmentList = dao.find("select * from department where parentId = 0");
			} else {
				departmentList = dao.find("select * from department where parentId = ?", Integer.parseInt(pid));
			}
			Department tmp = new Department();
			tmp.set("id", -1);
			tmp.set("name", "无上级部门");
			departmentList.add(tmp);
			renderJson(departmentList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取当前level下的全部部门信息
	 * */
	public void searchByLevel() {
		try {
			int level = getParaToInt("level");
			List<Department> departmentList = new ArrayList<Department>();
			Department tmp = new Department();
			tmp.set("id", 0);
			tmp.set("name", "无上级部门，默认为一级部门");
			departmentList.add(tmp);
			if(level>0) {
				departmentList.addAll(dao.find("select * from department where level = ?", level-1));
			}
			renderJson(departmentList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据ID查找该部门下是否存在子部门
	 */
	public void checkChildDept() {
		AjaxDone j = new AjaxDone();
		try {
			int id = getParaToInt("id");
			List<Department> deptList = dao.find("SELECT * FROM department WHERE parentId = ?", id);
			if(deptList!=null && deptList.size() > 0) {
				j.setErrorMsg("该部门下存在子部门，是否继续删除？");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderJson(j);
	}
	
	/**
	 * 根据ID删除对应的部门信息
	 */
	@Before(Tx.class)
	public void doDelete() {
		AjaxDone j = new AjaxDone();
		try {
			int id = getParaToInt("id");
			//先删除子部门
			List<Department> deptList = dao.find("SELECT * FROM department WHERE parentId = ?", id);
			if(deptList!=null && deptList.size() > 0) {
				for (Department department : deptList) {
					doCascadeDelete(department);
				}
			}
			//再删除当前部门
			dao.deleteById(id);
		} catch (Exception e) {
			j.setErrorMsg("删除过程中发生异常：" + e.getMessage());
			e.printStackTrace();
		}
		renderJson(j);
	}
	
	/**
	 * 加载修改部门页面信息
	 */
	public void goUpdate() {
		AjaxDone j = new AjaxDone();
		try {
			int id = getParaToInt("id");
			if(id == 0) {
				j.setErrorMsg("请选择要修改的部门!");
				renderJson(j);
			} else {
				Department dept = dao.findById(id);
				//拼装dto
				Map<String, Object> resultMap = new HashMap<String, Object>();
				resultMap.put("department.name", dept.getStr("name"));
				resultMap.put("department.deptId", dept.getStr("deptId"));
				resultMap.put("department.level", dept.getInt("level"));
				resultMap.put("level", dept.getInt("level"));
				resultMap.put("parentId", dept.getInt("parentId"));
				renderJson(resultMap);
			}
		} catch (Exception e) {
			j.setErrorMsg("修改过程中发生异常：" + e.getMessage());
			renderJson(j);
		}
	}
	
	public void doUpdate() {
		AjaxDone j = new AjaxDone();
		try {
			if(!getModel(Department.class).update()){
				j.setErrorMsg("修改失败!");
			}
		} catch (Exception e) {
			j.setErrorMsg("修改过程中发生错误：" + e.getMessage());
		}
		renderJson(j);
	}

	/**
	 * 获取所有部门信息
	 */
	public void searchAllDept() {
		AjaxDone j = new AjaxDone();
		try {
			List<Department> parentList = dao.find("select * from department where level = 1");
			List<Department> resultList = new ArrayList<Department>();
			if(parentList!=null && parentList.size()>0) {
				for (Department parent : parentList) {
					resultList.add(parent);
					recursionDept(resultList, parent, "--");
				}
			}
			renderJson(resultList);
		} catch (Exception e) {
			j.setErrorMsg("获取单位列表出错:" + e.getMessage());
			renderJson(j);
		}
	}
	
	/**
	 * 递归获取子菜单
	 * */
	private static void recursionDept(List<Department> deptList, Department parent, String subStr) throws Exception {
		List<Department> list = Department.dao.find("select * from department where parentId = ?", parent.getInt("id"));
		for (Department department : list) {
			department.set("name", subStr + department.getStr("name"));
			deptList.add(department);
			recursionDept(deptList, department, "--" + subStr);
		}
	}
	
	//级联删除部门信息
	private static void doCascadeDelete(Department department) throws Exception {
		List<Department> deptList = department.find("SELECT * FROM department WHERE parentId = ?", department.getInt("id"));
		if(deptList!=null && deptList.size() > 0) {
			for (Department _department : deptList) {
				doCascadeDelete(_department);
				department.delete();
			}
		}
		department.delete();
	}

}
